import requests
from loguru import logger

from const import ENV_DIR
from lib.parser import parser_file


class BaseAPI(object):
    MER_HOST = ""
    USER_HOST = ""

    def send_merchant_request(self, api_name, data: dict):
        if self.MER_HOST:
            data.update({"url": self.MER_HOST + data["url"]})
        logger.info(f"{api_name}接口请求数据为：{data}")
        r = requests.request(**data)
        logger.info(f"{api_name}接口响应数据为：{r.text}")
        return r.json()

    def send_user_request(self, api_name, data: dict):
        if self.USER_HOST:
            data.update({"url": self.USER_HOST + data["url"]})
        logger.info(f"{api_name}接口请求数据为：{data}")
        r = requests.request(**data)
        logger.info(f"{api_name}接口响应数据为：{r.text}")
        return r.json()


class Login(BaseAPI):

    def __init__(self):
        path = str(ENV_DIR / "test.yaml")
        requests_data = parser_file(path)
        self.merchant_data = requests_data["MERCHANT"]
        self.user_data = requests_data["USER"]
        # 测试环境
        self.MER_HOST = self.merchant_data["host"]
        self.USER_HOST = self.user_data["host"]
        # 开发环境
        self.merchant_token = self.merchant_login()["data"]["token"]
        self.user_token = self.user_login()["data"]["token"]
        # self.token = self.plantform_login()["data"]["token"]

    def merchant_login(self):
        api_name = "merchant_login"
        data = {
            "url": "/api/admin/merchant/login",
            "method": "post",
            "headers": {'content-type': 'application/json', },
            "json": {
                'account': "17300000000",
                'pwd': '000000',
                'captchaVO': {},
                'captcha': {
                    'captchaVerification': '',
                    'secretKey': '',
                    'token': '',
                },
            }
        }
        return self.send_merchant_request(api_name, data)

    def user_login(self):
        api_name = "user_login"
        data = {
            "url": "/api/front/login/mobile/password",
            "method": "post",
            "headers": {'content-type': 'application/json', },
            "json": {**self.user_data["user_login"],
                     'spreadPid': 0,
                     }
        }
        return self.send_user_request(api_name, data)
